/**
 * setCookie
 * @param {*} key 
 * @param {*} value 
 * @param {*} maxAge
 */
export function setCookie(key, value, maxAge = null) {    
    if (typeof value !== 'string') {
        value = JSON.stringify(value)
    }

    if (maxAge && !isNaN(parseInt(maxAge))) {
        let lifeTime = new Date().getTime()
        document.cookie = key + "=" + value + ";expires=" + new Date(lifeTime + maxAge * 1000).toGMTString() + ";path=/";
    }else{
        document.cookie = key + "=" + value + ";path=/";
    }
};
    
/**
 * getCookie
 * @param {*} key 
 * @returns 
 */
export function getCookie(key) {
    var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        const value = arr[2];
        if (typeof value !== 'string') {
            return JSON.parse(value)
        }else{
            return value;
        }
    }else{
      return null;
    }
}
  
/**
 * delCookie
 * @param {*} key 
 */
export function delCookie(key) {
    let lifeTime = new Date().getTime()
    var cval = getCookie(key);
    if (cval != key)
        document.cookie = key + "=" + cval + ";expires=" + new Date(lifeTime - 1).toGMTString() + ";path=/";
};

export default {
    getCookie,
    setCookie,
    delCookie,
}
